﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Routing;
using System.Web.Compilation;
using System.Security;

namespace THS.HtmlHelpers
{
	/// <summary>
	/// The IRoutablePage interface allows us to pass the RequestContext to our WebForm
	/// </summary>
	public interface IRoutablePage
	{
		RoutingHelper Routing { get; set; }
	}

	/// <summary>
	/// WebFormRouteHandler - See Phil Haack's post at http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx
	/// </summary>
	public class WebFormRouteHandler : IRouteHandler
	{
		public WebFormRouteHandler( string virtualPath ): this( virtualPath, true )
		{
		}

		public WebFormRouteHandler( string virtualPath, bool checkPhysicalUrlAccess )
		{
			this.VirtualPath = virtualPath;
			this.CheckPhysicalUrlAccess = checkPhysicalUrlAccess;
		}

		public string VirtualPath { get; private set; }

		public bool CheckPhysicalUrlAccess { get; set; }

		public IHttpHandler GetHttpHandler( RequestContext requestContext )
		{
			if ( this.CheckPhysicalUrlAccess && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
				this.VirtualPath,
				requestContext.HttpContext.User,
				requestContext.HttpContext.Request.HttpMethod ) )
			{
				throw new SecurityException();
			}

			var page = BuildManager.CreateInstanceFromVirtualPath(
				this.VirtualPath,
				typeof( Page ) ) as IHttpHandler;

			if ( page != null )
			{
				var routablePage = page as IRoutablePage;

				if ( routablePage != null ) routablePage.Routing = new RoutingHelper( requestContext );
			}

			return page;
		}
	}
}